<template>
  <div class="balance-records-page">
    <div class="container">
      <div class="page-header">
        <el-button @click="handleBack" :icon="ArrowLeft" circle />
        <h1>余额明细</h1>
        <div class="placeholder"></div>
      </div>

      <!-- 余额概览 -->
      <el-card class="balance-overview">
        <div class="overview-content">
          <div class="balance-info">
            <h2>当前余额</h2>
            <p class="balance-amount">¥{{ formatAmount(currentBalance) }}</p>
          </div>
          <div class="balance-stats">
            <div class="stat-item">
              <span class="label">本月收入</span>
              <span class="value income">+¥{{ formatAmount(monthlyStats.income) }}</span>
            </div>
            <div class="stat-item">
              <span class="label">本月支出</span>
              <span class="value expense">-¥{{ formatAmount(monthlyStats.expense) }}</span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 筛选条件 -->
      <el-card class="filter-section">
        <el-form :model="filters" :inline="true">
          <el-form-item label="交易类型">
            <el-select v-model="filters.type" placeholder="全部类型" clearable>
              <el-option label="全部" value="" />
              <el-option label="充值" value="recharge" />
              <el-option label="消费" value="payment" />
              <el-option label="退款" value="refund" />
              <el-option label="提现" value="withdraw" />
              <el-option label="赠送" value="gift" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filters.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">筛选</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 交易记录列表 -->
      <el-card class="records-list">
        <div class="list-header">
          <h3>交易记录</h3>
          <el-button link @click="exportRecords">导出明细</el-button>
        </div>

        <div class="records-content" v-loading="loading">
          <div
            v-for="record in records"
            :key="record.id"
            class="record-item"
            @click="showRecordDetail(record)"
          >
            <div class="record-icon">
              <el-icon 
                :size="24" 
                :color="getRecordIconColor(record.type)"
              >
                <component :is="getRecordIcon(record.type)" />
              </el-icon>
            </div>

            <div class="record-content">
              <div class="record-header">
                <h4>{{ record.description }}</h4>
                <span class="record-amount" :class="getAmountClass(record.type)">
                  {{ getAmountPrefix(record.type) }}¥{{ formatAmount(record.amount) }}
                </span>
              </div>
              <div class="record-meta">
                <span class="record-time">{{ formatDateTime(record.createdAt) }}</span>
                <el-tag 
                  :type="getStatusTag(record.status)" 
                  size="small"
                >
                  {{ getStatusText(record.status) }}
                </el-tag>
              </div>
              <div class="record-extra" v-if="record.orderNumber">
                <span class="order-number">订单号：{{ record.orderNumber }}</span>
              </div>
            </div>

            <div class="record-balance">
              <span class="balance-after">余额：¥{{ formatAmount(record.balanceAfter) }}</span>
            </div>
          </div>

          <div v-if="records.length === 0 && !loading" class="empty-records">
            <el-empty description="暂无交易记录" :image-size="100" />
          </div>
        </div>

        <!-- 加载更多 -->
        <div class="load-more" v-if="hasMore && !loading">
          <el-button @click="loadMore" :loading="loadingMore">
            加载更多
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 记录详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="交易详情"
      width="500px"
    >
      <div class="record-detail" v-if="selectedRecord">
        <div class="detail-row">
          <span class="label">交易类型</span>
          <span class="value">{{ getTypeText(selectedRecord.type) }}</span>
        </div>
        <div class="detail-row">
          <span class="label">交易金额</span>
          <span class="value amount" :class="getAmountClass(selectedRecord.type)">
            {{ getAmountPrefix(selectedRecord.type) }}¥{{ formatAmount(selectedRecord.amount) }}
          </span>
        </div>
        <div class="detail-row">
          <span class="label">交易时间</span>
          <span class="value">{{ formatDateTime(selectedRecord.createdAt) }}</span>
        </div>
        <div class="detail-row">
          <span class="label">交易状态</span>
          <el-tag 
            :type="getStatusTag(selectedRecord.status)" 
            size="small"
          >
            {{ getStatusText(selectedRecord.status) }}
          </el-tag>
        </div>
        <div class="detail-row" v-if="selectedRecord.orderNumber">
          <span class="label">关联订单</span>
          <el-button 
            link 
            type="primary" 
            @click="goToOrder(selectedRecord.orderNumber)"
          >
            {{ selectedRecord.orderNumber }}
          </el-button>
        </div>
        <div class="detail-row">
          <span class="label">交易前余额</span>
          <span class="value">¥{{ formatAmount(selectedRecord.balanceBefore) }}</span>
        </div>
        <div class="detail-row">
          <span class="label">交易后余额</span>
          <span class="value">¥{{ formatAmount(selectedRecord.balanceAfter) }}</span>
        </div>
        <div class="detail-row" v-if="selectedRecord.remark">
          <span class="label">备注</span>
          <span class="value">{{ selectedRecord.remark }}</span>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft,
  Wallet,
  ShoppingBag,
  Plus,
  Minus,
  RefreshRight,
  Gift,
  CreditCard
} from '@element-plus/icons-vue'
import { accountApi } from '@/services/api'
import dayjs from 'dayjs'

const router = useRouter()

// 数据定义
const records = ref([])
const loading = ref(true)
const loadingMore = ref(false)
const hasMore = ref(true)
const page = ref(1)
const pageSize = ref(10)
const currentBalance = ref(0)
const showDetailDialog = ref(false)
const selectedRecord = ref(null)

const monthlyStats = reactive({
  income: 0,
  expense: 0
})

const filters = reactive({
  type: '',
  dateRange: []
})

// 生命周期
onMounted(() => {
  fetchBalanceInfo()
  fetchRecords()
  fetchMonthlyStats()
})

// 方法定义
const fetchBalanceInfo = async () => {
  try {
    const response = await accountApi.getAccountInfo()
    currentBalance.value = response.data.balance
  } catch (error) {
    console.error('获取余额信息失败:', error)
  }
}

const fetchRecords = async (reset = true) => {
  try {
    if (reset) {
      loading.value = true
      page.value = 1
    } else {
      loadingMore.value = true
    }

    const params = {
      page: page.value,
      pageSize: pageSize.value,
      type: filters.type || undefined,
      startDate: filters.dateRange?.[0],
      endDate: filters.dateRange?.[1]
    }

    const response = await accountApi.getBalanceRecords(params)
    const { data, total } = response.data
    
    if (reset) {
      records.value = data
    } else {
      records.value.push(...data)
    }

    hasMore.value = records.value.length < total
  } catch (error) {
    console.error('获取余额记录失败:', error)
    ElMessage.error('获取余额记录失败')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

const fetchMonthlyStats = async () => {
  try {
    const response = await accountApi.getMonthlyBalanceStats()
    Object.assign(monthlyStats, response.data)
  } catch (error) {
    console.error('获取月度统计失败:', error)
  }
}

const handleSearch = () => {
  fetchRecords()
}

const handleReset = () => {
  filters.type = ''
  filters.dateRange = []
  fetchRecords()
}

const loadMore = () => {
  page.value++
  fetchRecords(false)
}

const showRecordDetail = (record) => {
  selectedRecord.value = record
  showDetailDialog.value = true
}

const exportRecords = async () => {
  try {
    const response = await accountApi.exportBalanceRecords(filters)
    // 处理文件下载
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `余额明细_${dayjs().format('YYYY-MM-DD')}.xlsx`)
    document.body.appendChild(link)
    link.click()
    link.remove()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

const goToOrder = (orderNumber) => {
  // 根据订单号跳转到订单详情
  router.push(`/orders/${orderNumber}`)
}

const handleBack = () => {
  router.back()
}

const getRecordIcon = (type) => {
  const iconMap = {
    recharge: Plus,
    payment: ShoppingBag,
    refund: RefreshRight,
    withdraw: Minus,
    gift: Gift
  }
  return iconMap[type] || Wallet
}

const getRecordIconColor = (type) => {
  const colorMap = {
    recharge: '#67c23a',
    payment: '#f56c6c',
    refund: '#409eff',
    withdraw: '#e6a23c',
    gift: '#9c27b0'
  }
  return colorMap[type] || '#909399'
}

const getAmountClass = (type) => {
  return ['recharge', 'refund', 'gift'].includes(type) ? 'income' : 'expense'
}

const getAmountPrefix = (type) => {
  return ['recharge', 'refund', 'gift'].includes(type) ? '+' : '-'
}

const getTypeText = (type) => {
  const textMap = {
    recharge: '充值',
    payment: '消费',
    refund: '退款',
    withdraw: '提现',
    gift: '赠送'
  }
  return textMap[type] || '未知'
}

const getStatusTag = (status) => {
  const tagMap = {
    success: 'success',
    pending: 'warning',
    failed: 'danger'
  }
  return tagMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    success: '成功',
    pending: '处理中',
    failed: '失败'
  }
  return textMap[status] || '未知'
}

const formatAmount = (amount) => {
  return parseFloat(amount || 0).toFixed(2)
}

const formatDateTime = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}
</script>

<style lang="scss" scoped>
.balance-records-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  h1 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
  }

  .placeholder {
    width: 32px;
  }
}

.el-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.balance-overview {
  .overview-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .balance-info {
      h2 {
        margin: 0 0 8px 0;
        font-size: 16px;
        color: #666;
      }

      .balance-amount {
        margin: 0;
        font-size: 32px;
        font-weight: 600;
        color: #333;
      }
    }

    .balance-stats {
      display: flex;
      flex-direction: column;
      gap: 8px;
      text-align: right;

      .stat-item {
        display: flex;
        flex-direction: column;
        gap: 4px;

        .label {
          font-size: 12px;
          color: #999;
        }

        .value {
          font-size: 16px;
          font-weight: 600;

          &.income {
            color: #67c23a;
          }

          &.expense {
            color: #f56c6c;
          }
        }
      }
    }
  }
}

.filter-section {
  :deep(.el-form) {
    margin: 0;
  }

  :deep(.el-form-item) {
    margin-bottom: 0;
  }
}

.records-list {
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }
  }

  .records-content {
    .record-item {
      display: flex;
      align-items: center;
      padding: 16px 0;
      border-bottom: 1px solid #f0f2f5;
      cursor: pointer;
      transition: background-color 0.3s ease;

      &:hover {
        background-color: #f8f9fa;
        margin: 0 -20px;
        padding: 16px 20px;
        border-radius: 8px;
      }

      &:last-child {
        border-bottom: none;
      }

      .record-icon {
        margin-right: 16px;
        width: 48px;
        height: 48px;
        border-radius: 24px;
        background-color: #f5f7fa;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
      }

      .record-content {
        flex: 1;
        min-width: 0;

        .record-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 4px;

          h4 {
            margin: 0;
            font-size: 14px;
            font-weight: 500;
            color: #333;
            flex: 1;
            margin-right: 12px;
          }

          .record-amount {
            font-size: 16px;
            font-weight: 600;
            white-space: nowrap;

            &.income {
              color: #67c23a;
            }

            &.expense {
              color: #f56c6c;
            }
          }
        }

        .record-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 4px;

          .record-time {
            font-size: 12px;
            color: #999;
          }
        }

        .record-extra {
          .order-number {
            font-size: 12px;
            color: #666;
          }
        }
      }

      .record-balance {
        margin-left: 16px;
        text-align: right;
        flex-shrink: 0;

        .balance-after {
          font-size: 12px;
          color: #999;
          white-space: nowrap;
        }
      }
    }

    .empty-records {
      padding: 60px 0;
      text-align: center;
    }
  }

  .load-more {
    text-align: center;
    margin-top: 20px;
  }
}

.record-detail {
  .detail-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f2f5;

    &:last-child {
      border-bottom: none;
    }

    .label {
      font-size: 14px;
      color: #666;
      min-width: 80px;
    }

    .value {
      font-size: 14px;
      color: #333;
      text-align: right;
      flex: 1;

      &.amount {
        font-weight: 600;

        &.income {
          color: #67c23a;
        }

        &.expense {
          color: #f56c6c;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .balance-overview {
    .overview-content {
      flex-direction: column;
      gap: 16px;
      text-align: center;

      .balance-stats {
        flex-direction: row;
        justify-content: space-around;
        gap: 16px;
      }
    }
  }

  .filter-section {
    :deep(.el-form) {
      flex-direction: column;
      gap: 16px;

      .el-form-item {
        margin-right: 0;
      }
    }
  }

  .record-item {
    flex-direction: column;
    align-items: stretch !important;
    gap: 12px;

    .record-icon {
      align-self: flex-start;
    }

    .record-balance {
      margin-left: 0 !important;
      text-align: left;
    }
  }
}
</style> 